package me.tonywang.security.util;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.StringUtils;

import java.util.*;

public class FilterInvocationSecurityMetadataSourceUtils {

    public final static FilterInvocationSecurityMetadataSource createExpressionBasedFilterInvocationSecurityMetadataSource(Map<String, String> urlMap) {
        LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap(urlMap.size());
        for (Map.Entry<String, String> entry : urlMap
                .entrySet()) {
            RequestMatcher requestMatcher = new AntPathRequestMatcher(entry.getKey());
            Set<String> set = StringUtils.commaDelimitedListToSet(entry.getValue());
            Collection<ConfigAttribute> configAttributes = new LinkedHashSet<>(set.size());
            for (String str : set) {
                configAttributes.add(new SecurityConfig(str));
            }
            requestMap.put(requestMatcher, configAttributes);

        }
        return new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap, new DefaultWebSecurityExpressionHandler());
    }
}
